package br.com.quad.dao;

import java.util.List;

import br.com.quad.bean.Acessorio;
import br.com.quad.dao.HibernateDAOFactory;

public class AcessorioDAOHibernate implements AcessorioDAO {


	HibernateDAOFactory hibernateDAOFactory = null;
	HibernateDAO<Acessorio> hibernateDAO = null;

	public AcessorioDAOHibernate() {
		hibernateDAOFactory = new HibernateDAOFactory();
		hibernateDAO = hibernateDAOFactory.getAcessorioDAO();
	}
	
	
	@Override
	public boolean inserir(Acessorio acessorio) throws Exception {
		boolean ok = false;

		try {
			hibernateDAO.add(acessorio);
			ok = true;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 
		return ok;
	}

	@Override
	public boolean alterar(Acessorio acessorio) throws Exception {
		boolean ok = false;

		try {
			hibernateDAO.update(acessorio);
			ok = true;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}

		return ok;
	}

	@Override
	public boolean excluir(Acessorio acessorio) throws Exception {
		boolean ok = false;

		try {
			hibernateDAO.remove(acessorio);
			ok = true;
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		} 

		return ok;
	}

	@Override
	public Acessorio getAcessorio(int codigoAcessorio) {
		return hibernateDAO.get(codigoAcessorio);
		
	}

	@Override
	public List<Acessorio> getListarTodos() {
		return hibernateDAO.listAll();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Acessorio> getSelecionar(String descricao) {
		String 	sql = "FROM Acessorio WHERE codigoAcessorio <> 0";

		if (!(descricao.isEmpty())) {
			sql += " AND descricao like '" + descricao + "%' ";  
		}
					
		sql += " ORDER BY descricao";		
 
		List<Acessorio> lista = hibernateDAO.getSession().createQuery(sql).list();
		
		return lista;
	}
	

	@Override
	public boolean isExclusaoLiberada(Acessorio acessorio) {
		// TODO Auto-generated method stub
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean isExiste(Acessorio acessorio) {
		// SQL para verificar se a Acessorio existe
		String 	sql = 	" FROM Acessorio " +
						" WHERE descricao	= '"+ acessorio.getDescricao() + "' AND " +
						"		codigoAcessorio != '" + acessorio.getCodigoAcessorio() + "'";

		List<Acessorio> lista = hibernateDAO.getSession().createQuery(sql).list();
	    
		if (lista.size()<1) {
			return false;
		} else {
			return true;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Acessorio> getSelecionarTipoVeiculo(int codigoTipoVeiculo) {
		String sql ="SELECT t.acessorios " +
					" FROM TipoVeiculo as t " +
					" WHERE t.codigoTipoVeiculo = "+codigoTipoVeiculo;

		List<Acessorio> lista = hibernateDAO.getSession().createQuery(sql).list();
		
		return lista;
	}
}
